#include <cstdio>
#include <cstring>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <memory>
#include "Thread.hpp"
#include "Mutex.hpp"

int tickets= 10000;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;


void *getTicket(void *args)
{
    // other code
    std::string username = static_cast<const char *>(args);
    // ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        // 加锁和解锁的过程多个线程串行执行的，程序变慢了！
        // 锁只规定互斥访问，没有规定必须让谁优先执行
        // 锁就是真是的让多个执行流进行竞争的结果
        // pthread_mutex_lock(&lock);
        // pthread_mutex_lock(&lock);
        {
            LockGuard lockguard(&lock); // RAII风格的加锁！
            if (tickets > 0)
            {
                // 值得抢
                //  std::cout << td->threadname_ << " 正在进行抢票: "<< tickets << std::endl;
                std::cout << username << " 正在进行抢票: " << tickets << std::endl;
                // 用这段时间来模拟真实的抢票要花费的时间
                tickets--;
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
       
    }


    return nullptr;
}

int main()
{
    
    pthread_t t1, t2, t3, t4;
    

    std::unique_ptr<Thread> thread1(new Thread(getTicket, (void *)"user1", 1));
    std::unique_ptr<Thread> thread2(new Thread(getTicket, (void *)"user2", 2));
    std::unique_ptr<Thread> thread3(new Thread(getTicket, (void *)"user3", 3));
    std::unique_ptr<Thread> thread4(new Thread(getTicket, (void *)"user4", 4));

    thread1->join();
    thread2->join();
    thread3->join();
    thread4->join();

    return 0;
}